package com.mti.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import com.mti.component.snowflake.KeyWorker;
import com.mti.dao.model.KmZdryTypeEntity;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.configuration.SystemConfig;
import com.mti.dao.dto.LfZdryDto;
import com.mti.dao.dto.ZdryDto;
import com.mti.dao.model.LfZdryBaseEntity;
import com.mti.dao.model.TKmDailyCheckEntity;
import com.mti.dao.qo.TkmDCheckQo;
import com.mti.mapper.TKmDailyCheckMapper;
import com.mti.service.ILfZdryService;
import com.mti.service.LfZdryBaseService;
import com.mti.service.TKmDailyCheckService;
import com.mti.utils.UUIDUtils;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * @Classname TKmDailyCheckServiceImpl
 * @Description TODO
 * @Date 2020/2/27 17:01
 * @Created by duchaof
 * @Version 1.0
 */
@Service
@Slf4j
public class TKmDailyCheckServiceImpl extends ServiceImpl<TKmDailyCheckMapper, TKmDailyCheckEntity> implements TKmDailyCheckService {
    @Autowired
    private ILfZdryService iLfZdryService;

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    private LfZdryBaseService lfZdryBaseService;

    private static final List<String> exectTitle = Arrays.asList("姓名", "身份证", "户籍地","人员大类","人员小类","管控单位",
            "管控民警","稳控状态","核查日期","核查结果");

    @Override
    @Transactional
    public Object saveTKmDailyCheck(TKmDailyCheckEntity tKmDailyCheckEntity) {
        tKmDailyCheckEntity.setId(String.valueOf(KeyWorker.nextId()));
        String[] array = tKmDailyCheckEntity.getFileUrl().split(";");
        for(int i=0;i<array.length;i++){
            if(array[i].startsWith("http://")){
                continue;
            }
            StringBuilder sb = new StringBuilder(systemConfig.getFileDownloadIp());
            array[i]= sb.append(array[i]).toString();
        }

        tKmDailyCheckEntity.setFileUrl(String.join(";",array));
        return this.save(tKmDailyCheckEntity);
    }

    @Override
    public IPage<TKmDailyCheckEntity> queryTkmDailyCheckPage(TkmDCheckQo tkmDCheckQo) {
        Page<TKmDailyCheckEntity> page = new Page<>(tkmDCheckQo.getStart(),tkmDCheckQo.getSize());
        IPage<TKmDailyCheckEntity> data = this.getBaseMapper().queryTkmDailyCheckPage(page,tkmDCheckQo);
        handleDailyCheckData(data.getRecords());
        return data;
    }

    @Override
    public Mono<DataBuffer> exportDailyCheck(String exportName, String keyWords, String startTime, String endTime,
                                             String checkResult,String ssfj,String sspcs,String jz) {
        TkmDCheckQo tkmDCheckQo = new TkmDCheckQo(keyWords,startTime,endTime,checkResult,ssfj,sspcs,jz);

        List<TKmDailyCheckEntity> dailyCheckList = this.getBaseMapper().queryexportDailyCheckData(tkmDCheckQo);
        handleDailyCheckData(dailyCheckList);

        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        CellStyle cellStyleCenter = wb.createCellStyle();
        CellStyle cellStyleLeft = wb.createCellStyle();
        cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
        cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
        cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
        cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);


        SXSSFSheet sh = wb.createSheet(exportName==null?"重点人员日常核查表":exportName);
        sh.trackAllColumnsForAutoSizing();

        int totalSize = 2 + dailyCheckList.size();
        for(int rowNum=0;rowNum<totalSize;rowNum++){
            Row row = sh.createRow(rowNum);
            for(int i=0;i<exectTitle.size();i++){
                Cell cell = row.createCell(i);
                if(rowNum==1){
                    cell.setCellValue(exectTitle.get(i));
                    cell.setCellStyle(cellStyleLeft);
                }
                if(rowNum>1){
                    TKmDailyCheckEntity data =  dailyCheckList.get(rowNum-2);
                    switch (i){
                        case 0: {
                            if(null != data.getZdryDto())
                               cell.setCellValue(data.getZdryDto().getXm());
                            }break;
                        case 1: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getZdryDto().getSfzh());
                        }break;
                        case 2: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getZdryDto().getHjd());
                        }break;
                        case 3: cell.setCellValue(data.getZdryDto().getRylbx());break;
                        case 4: cell.setCellValue(data.getZdryDto().getXl());break;
                        case 5: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getZdryDto().getSspcs());
                        }break;
                        case 6: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getZdryDto().getGkmj());
                        }break;
                        case 7: cell.setCellValue(data.getZdryDto().getWkzt());break;
                        case 8: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getCheckTime());
                        }break;
                        case 9: {
                            if(null != data.getZdryDto())
                            cell.setCellValue(data.getCheckResult());
                        }break;
                    }
                    cell.setCellStyle(cellStyleLeft);
                }
            }
            if (rowNum == 0) {
                sh.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
                StringBuilder sb = new StringBuilder("重点人员日常核查表");

                sh.getRow(rowNum).getCell(0).setCellValue(sb.toString());
                //设置单元格样式
                sh.getRow(rowNum).getCell(0).setCellStyle(cellStyleCenter);
            }
        }
        try {
            wb.write(outputStream);
        } catch (IOException e) {
            log.error("导出时发生异常：==>{}",e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("导出时发生异常：==>{}",e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }

    @Override
    public Object queryTkmDailyCheckList(TKmDailyCheckEntity tKmDailyCheckEntity) {
        QueryWrapper<TKmDailyCheckEntity> queryWrapper = new QueryWrapper<>();
        if(null!=tKmDailyCheckEntity.getId()){
            queryWrapper.lambda().eq(TKmDailyCheckEntity::getId,tKmDailyCheckEntity.getId());
        }
        if(null!=tKmDailyCheckEntity.getCheckResult()){
            queryWrapper.lambda().eq(TKmDailyCheckEntity::getCheckResult,tKmDailyCheckEntity.getCheckResult());
        }
        if(null!=tKmDailyCheckEntity.getCheckContent()){
            queryWrapper.lambda().like(TKmDailyCheckEntity::getCheckContent,tKmDailyCheckEntity.getCheckContent());
        }
        if(null!=tKmDailyCheckEntity.getRefId()){
            queryWrapper.lambda().eq(TKmDailyCheckEntity::getRefId,tKmDailyCheckEntity.getRefId());
        }
        List<TKmDailyCheckEntity> data = this.list(queryWrapper);
        handleDailyCheckData(data);
        return data;
    }

    private void handleDailyCheckData(List<TKmDailyCheckEntity> data){
        data.forEach(e->{
            LfZdryDto lfZdryDto = new LfZdryDto();
            lfZdryDto.setId(e.getRefId());
            List<ZdryDto> zdryDtoList = lfZdryBaseService.queryZdryByCondition(lfZdryDto);
            if(null !=zdryDtoList &&  zdryDtoList.size()>0) {
                ZdryDto zdry = zdryDtoList.get(0);
                e.setZdryDto(zdry); //设置重点人员
                // 设置重点人员的大类 小类
                if(null != zdry.getTypeList() && zdry.getTypeList().size()>0){
                    StringBuilder rylbx = new StringBuilder();
                    StringBuilder xl = new StringBuilder();
                    for(KmZdryTypeEntity t : zdry.getTypeList()){
                        if(rylbx.length()>0) rylbx.append("/").append(t.getRylb());
                        else rylbx.append(t.getRylb());
                        if(xl.length()>0) xl.append("/").append(t.getXl());
                        else xl.append(t.getXl());
                    }
                    zdry.setRylbx(rylbx.toString());
                    zdry.setXl(xl.toString());
                }
            }
        });
    }

}
